package com.daisuxia.web.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.utils.RequestUtils;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.web.pojo.JsAwardRecord;
import com.daisuxia.web.pojo.JsDrawrollsRecord;
import com.daisuxia.web.pojo.JsLoanPerson;
import com.daisuxia.web.pojo.JsStepConfig;
import com.daisuxia.web.pojo.JsStepRecord;
import com.daisuxia.web.service.IJsAwardRecordService;
import com.daisuxia.web.service.IJsDrawrollsRecordService;
import com.daisuxia.web.service.IJsLoanPersonService;
import com.daisuxia.web.service.IJsStepConfigService;
import com.daisuxia.web.service.IJsStepRecordService;
import com.daisuxia.web.util.StringUtils;


/**
 * 贷速侠帮助中心Controller
 * 
 * @author dhl
 * @version 2016-10-25
 */

//@RequestMapping(value = "${adminPath}/jsaward/awardCenter/")
@Controller
@RequestMapping("/jsaward/awardCenter")
public class AwardCenterController extends BaseController {
 
	private static Logger logger = LoggerFactory.getLogger(AwardCenterController.class);

	@Autowired
	private IJsLoanPersonService jsLoanPersonService;
	@Autowired
	private IJsAwardRecordService jsAwardRecordService;
	@Autowired
	private IJsDrawrollsRecordService jsDrawrollsRecordService;
	@Autowired
	private IJsStepConfigService jsStepConfigService;
	@Autowired
	private IJsStepRecordService jsStepRecordService;

//	@Autowired
// 
//	JedisCluster jedisCluster;
	/**
	 * 获取当期抽奖记录
	 * 
	 * @return
	 */
	public JsAwardRecord getCurrentjsAwardRecordOrInsert() {
		
		
		JsAwardRecord jsAwardRecord = new JsAwardRecord();
//		jsAwardRecord.setStatus(0);
		 
		HashMap<String,Object> paramsMap=new HashMap<String,Object>();
//		paramsMap.put("darwTime", new Date());
		 
		paramsMap.put("status", 0);
		jsAwardRecord = jsAwardRecordService.findOne(paramsMap);
 
		if (jsAwardRecord == null
				|| jsAwardRecord.getStatus().intValue() != JsAwardRecord.ZT_WKJ
						.intValue()) {
			BigDecimal minAwardMoney = new BigDecimal(500);// 默认最小金额奖金，需要修改成数据库配置
//			minAwardMoney =new BigDecimal(DictUtils.getDictLabel("minAwardMoney", "awardMoney", ""));
			minAwardMoney =new BigDecimal(0);
			jsAwardRecord = new JsAwardRecord();
			// 查询出最大的期数，如果没有从1开始。
			JsAwardRecord jsAwardRecordlast = null;
			
			 
//			paramsMap.put("darwTime", new Date());
			 
			paramsMap.clear();
			jsAwardRecordlast = jsAwardRecordService.findOne(paramsMap);
			 
			jsAwardRecord.setPeriods(jsAwardRecordlast != null
					? jsAwardRecordlast.getPeriods() + 1
					: 1);
			jsAwardRecord.setAwardMoney(minAwardMoney);
			jsAwardRecord.setMoneyUpdateTime(new Date());
			jsAwardRecord.setStatus(JsAwardRecord.ZT_WKJ);
			jsAwardRecordService.save(jsAwardRecord);// 更新到数据库
			logger.info("添加中奖期数记录==========" + jsAwardRecord.getPeriods());
		}

		return jsAwardRecord;
	}
	
	/**
	 * 获取当期抽奖记录
	 * 
	 * @return
	 */
	public JsAwardRecord getCurrentjsAwardRecord() {
		
		
		JsAwardRecord jsAwardRecord = new JsAwardRecord();
		jsAwardRecord.setStatus(0);
		
		HashMap<String,Object> paramsMap=new HashMap<String,Object>();
//		paramsMap.put("darwTime", new Date());
		 
		paramsMap.put("status", 0);
		jsAwardRecord = jsAwardRecordService.findOne(paramsMap);

//		if (jsAwardRecord == null
//				|| jsAwardRecord.getStatus().intValue() != JsAwardRecord.ZT_WKJ
//						.intValue()) {
//			BigDecimal minAwardMoney = new BigDecimal(500);// 默认最小金额奖金，需要修改成数据库配置
//			minAwardMoney =new BigDecimal(DictUtils.getDictLabel("minAwardMoney", "awardMoney", ""));
//			jsAwardRecord = new JsAwardRecord();
//			// 查询出最大的期数，如果没有从1开始。
//			JsAwardRecord jsAwardRecordlast = null;
//			jsAwardRecordlast = jsAwardRecordService.findOne(jsAwardRecordlast);
//			jsAwardRecord.setPeriods(jsAwardRecordlast != null
//					? jsAwardRecordlast.getPeriods() + 1
//					: 1);
//			jsAwardRecord.setAwardMoney(minAwardMoney);
//			jsAwardRecord.setMoneyUpdateTime(new Date());
//			jsAwardRecord.setStatus(JsAwardRecord.ZT_WKJ);
//			jsAwardRecordService.save(jsAwardRecord);// 更新到数据库
//			logger.info("添加中奖期数记录==========" + jsAwardRecord.getPeriods());
//		}

		return jsAwardRecord;
	}

	/**
	 * 获取当前用户
	 * 
	 * @return
	 */
	public JsLoanPerson getCurrentUser(String userPhone, String userName,
			String userCardNo) {

		// 查询用户是否存在，不存在添加
		JsLoanPerson user = new JsLoanPerson();
		user.setPhone(userPhone);
		// user=查询数据库
		user = jsLoanPersonService.findOne(user);
		if (user == null) {
			user = new JsLoanPerson();
			user.setPhone(userPhone);
//			user.setName(userName);
//			user.setIdNumber(userCardNo);
			user.setCreatedAt(new Date());
			user.setUpdatedAt(new Date());
			// 更新到数据库user
			jsLoanPersonService.save(user);
			logger.info("新增用户：" + user);

		}

		return user;
	}

	/**
	 * 根据期数创建抽奖号码
	 * 
	 * @param jsAwardRecord
	 * @return
	 */
	public Integer createLucyDraw(JsAwardRecord jsAwardRecord) {
		Integer lucyDraw = JsDrawrollsRecord.startNumber+1;
		JsDrawrollsRecord drawrollsLast = new JsDrawrollsRecord();
		drawrollsLast.setPeriods(jsAwardRecord.getPeriods());
		drawrollsLast = jsDrawrollsRecordService.findOne(drawrollsLast);
		if (drawrollsLast != null && drawrollsLast.getLuckyDraw() > 0) {
			lucyDraw = drawrollsLast.getLuckyDraw() + 1;
		}

		return lucyDraw;
	}

	/**
	 * 增加奖金池
	 * 
	 * @param jsAwardRecord
	 * @return
	 */
	public synchronized void addAwardManey(JsStepRecord stepRecord) {

		BigDecimal maxAwardMoney = new BigDecimal(100000);// 最大奖金数
//		maxAwardMoney =new BigDecimal(DictUtils.getDictLabel("maxAwardMoney", "awardMoney", ""));
//		maxAwardMoney =new BigDecimal(100000);
		// 获取当期抽奖记录
		JsAwardRecord jsAwardRecord = getCurrentjsAwardRecord();
		if (stepRecord.getEffectiveCount() > 0
				&& maxAwardMoney.subtract(jsAwardRecord.getAwardMoney())
						.compareTo(BigDecimal.ZERO) > 0) {
			JsAwardRecord jsAwardRecordNew = new JsAwardRecord();
			jsAwardRecordNew.setAwardMoney(jsAwardRecord.getAwardMoney().add(
					new BigDecimal(stepRecord.getEffectiveCount())));
			jsAwardRecordNew.setId(jsAwardRecord.getId());
			jsAwardRecordNew.setMoneyUpdateTime(new Date());
			// 更新到数据库jsAwardRecord
			jsAwardRecordService.save(jsAwardRecordNew);// 更新到数据库
			logger.info(stepRecord.getRemark() + "增加奖金池，目前奖金："
					+ jsAwardRecordNew.getAwardMoney());
		}

	}

	/**
	 * 添抽奖记录
	 * @param stepRecord
	 * @param user
	 * @param jsAwardRecord
	 */
	public synchronized void  addDrawrollsRecord(JsStepRecord stepRecord, JsLoanPerson user,
			JsAwardRecord jsAwardRecord) {
		for (int i = 0; i < stepRecord.getEffectiveCount(); i++) {
	 
			JsDrawrollsRecord drawrollsRecord = new JsDrawrollsRecord();
			drawrollsRecord.setStepId(stepRecord.getId());
			drawrollsRecord.setUserId(user.getId());
			drawrollsRecord.setAddTime(new Date());
			drawrollsRecord.setUpdateTime(new Date());
			drawrollsRecord.setPeriods(jsAwardRecord.getPeriods());
			drawrollsRecord.setLuckyDraw(createLucyDraw(jsAwardRecord));
			drawrollsRecord.setStatus(0);
			drawrollsRecord.setIsValid(1);
			jsDrawrollsRecordService.save(drawrollsRecord);
			logger.info(user.getPhone() + "添加一条抽奖记录");
 
			
		}

	}
	
	

	/**
	 * 添加行为
	 * @param user
	 * @param userStep
	 * @return
	 */
	public JsStepRecord addStepRecord(JsLoanPerson user, JsStepConfig userStep) {
		// 添加行为
		JsStepRecord stepRecord = new JsStepRecord();
		stepRecord.setUserId(user.getId());
		stepRecord.setStepId(userStep.getId());
		stepRecord.setRemark(userStep.getStepName());
		stepRecord.setAddTime(new Date());
		stepRecord.setUpdateTime(new Date());
		if (userStep.getStatus().intValue() == 1) {
			stepRecord.setEffectiveCount(userStep.getEffectiveCount());
		}
		jsStepRecordService.save(stepRecord);
		logger.info(user.getPhone() + "添加行为记录成功：");
		return stepRecord;
	}
	
	/**
	 * 添加行为后台
	 * @param user
	 * @param userStep
	 * @return
	 */
	public JsStepRecord addStepRecordBlack(JsLoanPerson user, JsStepConfig userStep) {
		// 添加行为
		JsStepRecord stepRecord = new JsStepRecord();
		stepRecord.setUserId(user.getId());
		stepRecord.setStepId(userStep.getId());
		stepRecord.setRemark("后台手动:"+userStep.getStepName());
		stepRecord.setAddTime(new Date());
		stepRecord.setUpdateTime(new Date());
		if (userStep.getStatus().intValue() == 1) {
			stepRecord.setEffectiveCount(userStep.getEffectiveCount());
		}
		jsStepRecordService.save(stepRecord);
		logger.info(user.getPhone() + "添加行为记录成功：");
		return stepRecord;
	}

	@RequestMapping(value = {"addUserStepOut", ""})
	public void addUserStepOut(
			HttpServletRequest request, HttpServletResponse response,
			Model model) {

		HashMap<String, Object> mapParams = new HashMap<String, Object>();
		ServiceResult serviceResult = new ServiceResult("500", "未知异常");

		try {
//			serviceResult =checkIpBlack(request);
//			if (!serviceResult.isSuccessed()) {
//				
//				BackUser backUser = loginAdminUser(request);
//			if(backUser!=null){
//				serviceResult.setCode(ServiceResult.SUCCESS);
//				serviceResult.setMsg("后台用户操作！");
//			}}
//			if (serviceResult.isSuccessed()) {
				mapParams = getParametersO(request);
				logger.info("request params==="+mapParams.toString());
				String userPhone = (String) mapParams.get("userPhone"); // 用户手机号
				String userName = String.valueOf(mapParams.get("userName"));// 用户姓名
				// userName=new String(userName.getBytes("ISO8859-1"),"UTF-8");

				String userCardNo = (String) mapParams.get("cardNum");// 身份证号
				String awardType = (String) mapParams.get("awardType");// 行为类型
				String invitePhone = (String) mapParams.get("invitePhone"); // 邀请人手机号
				
				if (userPhone == null || awardType == null) {
					serviceResult.setCode("500");
					serviceResult.setMsg("参数错误，请检查参数！");
					logger.info("参数问题：" + mapParams.toString());
					return;
				}
				// 获取当期抽奖记录
				JsAwardRecord jsAwardRecord = getCurrentjsAwardRecordOrInsert();
				// 查询当前用户********************************************
				JsLoanPerson currentUser = getCurrentUser(userPhone, userName,
						userCardNo);

				// 获取行为
				JsStepConfig userStep = null;
				List<JsStepConfig> jsSteps = jsStepConfigService.findList(null);// 查询数据库

				for (JsStepConfig stepTemp : jsSteps) {
					if (awardType.equals(stepTemp.getStepCode())
							&& !stepTemp.getStepCode().equals(
									JsStepConfig.STEP_INVITE)) {
						userStep = stepTemp;
						break;
					}
				}
				if (userStep != null) {
					// 如果是认证成功，保存姓名、身份证号
					if (userStep.getStepCode()
							.equals(JsStepConfig.STEP_APPROVE)) {
						if (StringUtils.isEmpty(currentUser.getName())
								|| StringUtils.isEmpty(currentUser
										.getIdNumber())) {
							if (userName == null || userCardNo == null) {
								serviceResult.setCode("500");
								serviceResult
										.setMsg("参数错误，请检查参数！认证通过userName、cardNum为必填项");
								logger.error("认证通过参数问题：" + mapParams.toString());

								return;
							} else {
								JsLoanPerson userTwo = new JsLoanPerson();
								userTwo.setId(currentUser.getId());
								userTwo.setName(userName);
								userTwo.setIdNumber(userCardNo);
								userTwo.setUpdatedAt(new Date());
								jsLoanPersonService.save(userTwo);
							}

						}
					}
					// 添加行为**************************************
					JsStepRecord stepRecord = addStepRecord(currentUser,
							userStep);

					// 根据行为添加抽奖号码记录**********************
					if (userStep.getStatus().intValue() == 1
							&& userStep.getEffectiveCount() > 0) {
						// 添加抽奖记录
						addDrawrollsRecord(stepRecord, currentUser,
								jsAwardRecord);
						// 增加奖金池
						addAwardManey(stepRecord);
					}
					// 如果是认证成功，判断是否有邀请人
					if (userStep.getStepCode()
							.equals(JsStepConfig.STEP_APPROVE)) {

						// 判断是否有邀请人
						if (invitePhone != null) {
							JsLoanPerson inviteuser = getCurrentUser(invitePhone,null,null);
//							if (inviteuser != null) {
							
							//更新用户邀请信息
								JsLoanPerson currentUserUpdate = new JsLoanPerson();
								currentUserUpdate.setId(currentUser.getId());
								currentUserUpdate.setInviteCode(inviteuser.getPhone());
								currentUserUpdate.setUpdatedAt(new Date());
								jsLoanPersonService.save(currentUserUpdate);
								logger.info("成功更新邀请用户信息！");
								JsStepConfig inviteUserStep = null;

								for (JsStepConfig stepTemp : jsSteps) {
									if (stepTemp.getStepCode().equals(
											JsStepConfig.STEP_INVITE)) {
										inviteUserStep = stepTemp;
										break;
									}
								}
								// 添加行为**************************************
								JsStepRecord stepRecordinvet = addStepRecord(
										inviteuser, inviteUserStep);

								// 根据行为添加抽奖号码记录
								if (inviteUserStep.getStatus().intValue() == 1
										&& stepRecordinvet.getEffectiveCount() > 0) {
									// 添加抽奖记录
									addDrawrollsRecord(stepRecordinvet,
											inviteuser, jsAwardRecord);
									// 增加奖金池
									addAwardManey(stepRecordinvet);
								}

//							} else {
//								logger.error("用户：" + userPhone + "推荐人:"
//										+ invitePhone + "不存在");
//							}

						}

					}
					serviceResult = new ServiceResult(ServiceResult.SUCCESS,
							"成功");
				} else {
					serviceResult.setCode("500");
					serviceResult.setMsg("行为不存在：" + mapParams.toString());
				}

//			}
			// System.out.println("1111");

		} catch (Exception e) {
			serviceResult.setCode("500");
			serviceResult.setMsg("系统错误！" );
			logger.error("system error==="+mapParams.toString());
			e.printStackTrace();
		} finally {
			logger.info("return==="+serviceResult.toString());
			SpringUtils.renderJson(response, serviceResult);
		}

 
	}
	@RequestMapping(value = {"addUserStepBlack", ""})
	public ServiceResult addUserStepBlack(
			HttpServletRequest request, HttpServletResponse response,
			Model model) {

		HashMap<String, Object> mapParams = new HashMap<String, Object>();
		ServiceResult serviceResult = new ServiceResult("500", "未知异常");

		try {
//			serviceResult = RequestUtils.checkIpBlack(request);
//			if (serviceResult.isSuccessed()) {
				mapParams = getParametersO(request);
				String userPhone = (String) mapParams.get("userPhone"); // 用户手机号
				String userName = String.valueOf(mapParams.get("userName"));// 用户姓名
				// userName=new String(userName.getBytes("ISO8859-1"),"UTF-8");

				String userCardNo = (String) mapParams.get("cardNum");// 身份证号
				String awardType = (String) mapParams.get("awardType");// 行为类型
				String invitePhone = (String) mapParams.get("invitePhone"); // 邀请人手机号

				if (userPhone == null || awardType == null) {
					serviceResult.setCode("500");
					serviceResult.setMsg("参数错误，请检查参数！");
					logger.info("参数问题：" + mapParams.toString());
					return serviceResult;
				}
				// 获取当期抽奖记录
				JsAwardRecord jsAwardRecord = getCurrentjsAwardRecordOrInsert();
				// 查询当前用户********************************************
				JsLoanPerson currentUser = getCurrentUser(userPhone, userName,
						userCardNo);

				// 获取行为
				JsStepConfig userStep = null;
				List<JsStepConfig> jsSteps = jsStepConfigService.findList(null);// 查询数据库

				for (JsStepConfig stepTemp : jsSteps) {
					if (awardType.equals(stepTemp.getStepCode())
							&& !stepTemp.getStepCode().equals(
									JsStepConfig.STEP_INVITE)) {
						userStep = stepTemp;
						break;
					}
				}
				if (userStep != null) {
					// 如果是认证成功，保存姓名、身份证号
					if (userStep.getStepCode()
							.equals(JsStepConfig.STEP_APPROVE)) {
						if (StringUtils.isEmpty(currentUser.getName())
								|| StringUtils.isEmpty(currentUser
										.getIdNumber())) {
							if (userName == null || userCardNo == null) {
								serviceResult.setCode("500");
								serviceResult
										.setMsg("参数错误，请检查参数！认证通过userName、cardNum为必填项");
								logger.error("认证通过参数问题：" + mapParams.toString());

								return serviceResult;
							} else {
								JsLoanPerson userTwo = new JsLoanPerson();
								userTwo.setId(currentUser.getId());
								userTwo.setName(userName);
								userTwo.setIdNumber(userCardNo);
								userTwo.setUpdatedAt(new Date());
								jsLoanPersonService.save(userTwo);
							}

						}
					}
					// 添加行为**************************************
					JsStepRecord stepRecord = addStepRecordBlack(currentUser,
							userStep);

					// 根据行为添加抽奖号码记录**********************
					if (userStep.getStatus().intValue() == 1
							&& userStep.getEffectiveCount() > 0) {
						// 添加抽奖记录
						addDrawrollsRecord(stepRecord, currentUser,
								jsAwardRecord);
						// 增加奖金池
						addAwardManey(stepRecord);
					}
					// 如果是认证成功，判断是否有邀请人
					if (userStep.getStepCode()
							.equals(JsStepConfig.STEP_APPROVE)) {

						// 判断是否有邀请人
						if (invitePhone != null) {
							JsLoanPerson inviteuser = new JsLoanPerson();
							inviteuser.setPhone(invitePhone);
							inviteuser = jsLoanPersonService
									.findOne(inviteuser);
							if (inviteuser != null) {
								JsLoanPerson currentUserUpdate = new JsLoanPerson();
								currentUserUpdate.setId(currentUser.getId());
								currentUserUpdate.setUpdatedAt(new Date());
								currentUserUpdate.setInviteCode(inviteuser.getPhone());
								jsLoanPersonService.save(currentUserUpdate);
								logger.info("成功更新邀请用户信息！");
								JsStepConfig inviteUserStep = null;

								for (JsStepConfig stepTemp : jsSteps) {
									if (stepTemp.getStepCode().equals(
											JsStepConfig.STEP_INVITE)) {
										inviteUserStep = stepTemp;
										break;
									}
								}
								// 添加行为**************************************
								JsStepRecord stepRecordinvet = addStepRecord(
										inviteuser, inviteUserStep);

								// 根据行为添加抽奖号码记录
								if (inviteUserStep.getStatus().intValue() == 1
										&& stepRecordinvet.getEffectiveCount() > 0) {
									// 添加抽奖记录
									addDrawrollsRecord(stepRecordinvet,
											inviteuser, jsAwardRecord);
									// 增加奖金池
									addAwardManey(stepRecordinvet);
								}

							} else {
								logger.error("用户：" + userPhone + "推荐人:"
										+ invitePhone + "不存在");
							}

						}

					}
					serviceResult = new ServiceResult(ServiceResult.SUCCESS,
							"成功");
				} else {
					serviceResult.setCode("500");
					serviceResult.setMsg("行为不存在：" + mapParams.toString());
				}

//			}
			// System.out.println("1111");

		} catch (Exception e) {
			serviceResult.setCode("500");
			serviceResult.setMsg("系统错误！" );
			e.printStackTrace();
		} finally {
			logger.info("return==="+serviceResult);
			return serviceResult;
		}

 
	}


	@RequestMapping(value = {"runDrawBlack", ""})
	public ServiceResult runDrawBlack( 
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		ServiceResult serviceResult = new ServiceResult("500", "系统异常！");
		try {
			String periods = request.getParameter("periods");

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Integer startNumber = JsDrawrollsRecord.startNumber;
			Long peopleCount = 0L;
			Long a = 0L;// 时间总和
			Integer three_index;// 第三方指数配置
			Integer awardNumber;// 中奖号码

			JsAwardRecord awardRecord = new JsAwardRecord();
//			awardRecord.setStatus(0);
//			awardRecord.setPeriods(Integer.parseInt(periods));
			HashMap<String,Object> paramsMap=new HashMap<String,Object>();
			paramsMap.put("status", 0);
			paramsMap.put("periods", Integer.parseInt(periods));
			awardRecord = jsAwardRecordService.findOne(paramsMap);
			if (awardRecord == null) {
				serviceResult.setMsg("当前期数不存在或者已经开奖！");
				return serviceResult;
			}
			three_index = awardRecord.getThreeIndex();
			if (three_index == null || three_index.intValue() < 1) {
				serviceResult.setMsg("请先录入第三方开奖指数！");

				return serviceResult;
			}

			// 获取当期参与人数
			List<JsDrawrollsRecord> recordsAll = new ArrayList<JsDrawrollsRecord>();
			JsDrawrollsRecord recordTemp1 = new JsDrawrollsRecord();
			recordTemp1.setPeriods(Integer.parseInt(periods));
			recordTemp1.setIsValid(1);
			recordsAll = jsDrawrollsRecordService.findList(recordTemp1);
			if (recordsAll == null || recordsAll.size() < 1) {
				serviceResult.setMsg("当前期数没有参与人员，无法开奖！");
				return serviceResult;
			} else {
				HashMap<String, String> usersmap = new HashMap<String, String>();
				for (JsDrawrollsRecord recordsUserT : recordsAll) {
					usersmap.put(recordsUserT.getUserId(),
							recordsUserT.getUserId());
				}
				peopleCount = Long.valueOf(usersmap.keySet().size());
			}

			// 参与开奖的时间，最后50条数据
			List<JsDrawrollsRecord> drawrollsRecords = new ArrayList<JsDrawrollsRecord>();
			JsDrawrollsRecord recordTemp = new JsDrawrollsRecord();
			recordTemp.setPeriods(Integer.parseInt(periods));
			recordTemp.setIsValid(1);
			drawrollsRecords = jsDrawrollsRecordService.findListTop(recordTemp);// 数据库查询前50条

			Long addTimes[] = new Long[50];
			for (int i = 0; i < drawrollsRecords.size(); i++) {
				JsDrawrollsRecord recordTimeTemp = drawrollsRecords.get(i);
				addTimes[i] = stringToLong(sdf.format(recordTimeTemp
						.getAddTime()));
			}
//			System.out
//					.println("最后参与抽奖时间：==========================================");
			// 计算时间总和
			for (Long temp : addTimes) {
				if (temp != null && temp > 0) {
//					System.out.println(temp);
					a += temp;
				}
			}
//			System.out
//					.println("最后参与抽奖时间：==========================================");
//			System.out.println("上证指数为(取整数)：" + three_index);
			Long yushu = (a + three_index) % peopleCount;
			awardNumber = startNumber + 1 + yushu.intValue();
//			System.out.println("中奖号码为：" + awardNumber);
			// System.out.println("参与开奖号码个数：" + peopleCount + "\n最小号码：" +
			// startNumber
			// + 1 + ",最大号码：" + startNumber + peopleCount);

			JsDrawrollsRecord awardRecordUser = new JsDrawrollsRecord();
			for (JsDrawrollsRecord recordsUserT : recordsAll) {
				JsDrawrollsRecord recordUpdate = new JsDrawrollsRecord();
				recordUpdate.setId(recordsUserT.getId());
				recordUpdate.setUpdateTime(new Date());
				if (recordsUserT.getLuckyDraw().intValue() == awardNumber
						.intValue()) {
					awardRecordUser = recordsUserT;
					recordUpdate.setStatus(2);
				} else {
					recordUpdate.setStatus(1);
				}
				jsDrawrollsRecordService.save(recordUpdate);
			}

			JsAwardRecord awardRecordUpdate = new JsAwardRecord();
			awardRecordUpdate.setId(awardRecord.getId());
			awardRecordUpdate.setUserId(awardRecordUser.getUserId());
			awardRecordUpdate.setDrawrollsId(awardRecordUser.getId());
			awardRecordUpdate
					.setDrawrollsNumber(awardRecordUser.getLuckyDraw());
			awardRecordUpdate.setDarwTime(new Date());
			awardRecordUpdate.setStatus(1);
			JsLoanPerson user = new JsLoanPerson();
			user.setId(awardRecordUser.getUserId());
			// user=查询数据库
			user = jsLoanPersonService.findOne(user);
			awardRecordUpdate.setUserName(user.getName());
			jsAwardRecordService.save(awardRecordUpdate);
			serviceResult = new ServiceResult(serviceResult.SUCCESS, "成功开奖！");
		} catch (Exception e) {
			e.printStackTrace();
			serviceResult.setMsg("系统错误！");
		} finally {
			 return  serviceResult;
		}
	}
	
	@RequestMapping(value = {"runDraw", ""})
	public void runDraw(
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		ServiceResult serviceResult = new ServiceResult("500", "系统异常！");
		try {
			String periods = request.getParameter("periods");

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Integer startNumber = JsDrawrollsRecord.startNumber;
			Long peopleCount = 0L;
			Long a = 0L;// 时间总和
			Integer three_index;// 第三方指数配置
			Integer awardNumber;// 中奖号码

			JsAwardRecord awardRecord = new JsAwardRecord();
//			awardRecord.setStatus(0);
//			awardRecord.setPeriods(Integer.parseInt(periods));
			
			HashMap<String,Object> paramsMap=new HashMap<String,Object>();
			paramsMap.put("status", 0);
			paramsMap.put("periods", Integer.parseInt(periods));
			awardRecord = jsAwardRecordService.findOne(paramsMap);
		 
			if (awardRecord == null) {
				serviceResult.setMsg("当前期数不存在或者已经开奖！");
				SpringUtils.renderJson(response, serviceResult);
			}
			three_index = awardRecord.getThreeIndex();
			if (three_index == null || three_index.intValue() < 1) {
				serviceResult.setMsg("请先录入第三方开奖指数！");

				return;
			}

			// 获取当期参与人数
			List<JsDrawrollsRecord> recordsAll = new ArrayList<JsDrawrollsRecord>();
			JsDrawrollsRecord recordTemp1 = new JsDrawrollsRecord();
			recordTemp1.setPeriods(Integer.parseInt(periods));
			recordTemp1.setIsValid(1);
			recordsAll = jsDrawrollsRecordService.findList(recordTemp1);
			if (recordsAll == null || recordsAll.size() < 1) {
				serviceResult.setMsg("当前期数没有参与人员，无法开奖！");
				return;
			} else {
				HashMap<String, String> usersmap = new HashMap<String, String>();
				for (JsDrawrollsRecord recordsUserT : recordsAll) {
					usersmap.put(recordsUserT.getUserId(),
							recordsUserT.getUserId());
				}
				peopleCount = Long.valueOf(usersmap.keySet().size());
			}

			// 参与开奖的时间，最后50条数据
			List<JsDrawrollsRecord> drawrollsRecords = new ArrayList<JsDrawrollsRecord>();
			JsDrawrollsRecord recordTemp = new JsDrawrollsRecord();
			recordTemp.setPeriods(Integer.parseInt(periods));
			recordTemp.setIsValid(1);
			drawrollsRecords = jsDrawrollsRecordService.findListTop(recordTemp);// 数据库查询前50条

			Long addTimes[] = new Long[50];
			for (int i = 0; i < drawrollsRecords.size(); i++) {
				JsDrawrollsRecord recordTimeTemp = drawrollsRecords.get(i);
				addTimes[i] = stringToLong(sdf.format(recordTimeTemp
						.getAddTime()));
			}
//			System.out
//					.println("最后参与抽奖时间：==========================================");
			// 计算时间总和
			for (Long temp : addTimes) {
				if (temp != null && temp > 0) {
//					System.out.println(temp);
					a += temp;
				}
			}
//			System.out
//					.println("最后参与抽奖时间：==========================================");
//			System.out.println("上证指数为(取整数)：" + three_index);
			Long yushu = (a + three_index) % peopleCount;
			awardNumber = startNumber + 1 + yushu.intValue();
			System.out.println("中奖号码为：" + awardNumber);
			// System.out.println("参与开奖号码个数：" + peopleCount + "\n最小号码：" +
			// startNumber
			// + 1 + ",最大号码：" + startNumber + peopleCount);

			JsDrawrollsRecord awardRecordUser = new JsDrawrollsRecord();
			for (JsDrawrollsRecord recordsUserT : recordsAll) {
				JsDrawrollsRecord recordUpdate = new JsDrawrollsRecord();
				recordUpdate.setId(recordsUserT.getId());
				recordUpdate.setUpdateTime(new Date());
				if (recordsUserT.getLuckyDraw().intValue() == awardNumber
						.intValue()) {
					awardRecordUser = recordsUserT;
					recordUpdate.setStatus(2);
				} else {
					recordUpdate.setStatus(1);
				}
				jsDrawrollsRecordService.save(recordUpdate);
			}

			JsAwardRecord awardRecordUpdate = new JsAwardRecord();
			awardRecordUpdate.setId(awardRecord.getId());
			awardRecordUpdate.setUserId(awardRecordUser.getUserId());
			awardRecordUpdate.setDrawrollsId(awardRecordUser.getId());
			awardRecordUpdate
					.setDrawrollsNumber(awardRecordUser.getLuckyDraw());
			awardRecordUpdate.setDarwTime(new Date());
			awardRecordUpdate.setStatus(1);
			JsLoanPerson user = new JsLoanPerson();
			user.setId(awardRecordUser.getUserId());
			// user=查询数据库
			user = jsLoanPersonService.findOne(user);
			awardRecordUpdate.setUserName(user.getName());
			jsAwardRecordService.save(awardRecordUpdate);
			serviceResult = new ServiceResult(serviceResult.SUCCESS, "成功开奖！");
		} catch (Exception e) {
			e.printStackTrace();
			serviceResult.setMsg("系统错误！");
		} finally {
			SpringUtils.renderJson(response, serviceResult);
		}
	}

	public Long stringToLong(String str) {

		String regEx = "[^0-9]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		// 替换与模式匹配的所有字符（即非数字的字符将被""替换）
		return Long.parseLong(m.replaceAll("").trim());

	}

	@RequestMapping("drawAwardIndex")
	public String drawAwardIndex(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		JsAwardRecord jsAwardRecord = new JsAwardRecord();
		String clientType=request.getParameter("clientType");
		String isApp=request.getParameter("app");
		 if(isApp!=null&&isApp.equals("1")){
			 isApp="1";
		 }else{
			 isApp="0";
		 }
		String downUrl="http://a.app.qq.com/o/simple.jsp?pkgname=com.innext.dsx";
		if(clientType!=null&&clientType.equals("ios")){
			clientType="ios";
			downUrl="https://itunes.apple.com/cn/app/ji-su-xian-jin-xia/id1156341826?mt=8";
		}else{
			clientType="andriod";
		}
		//TODO songss 统计用户中奖记录
		JsAwardRecord jsAwardRecordykj = new JsAwardRecord();
		jsAwardRecordykj.setDarwTime(new Date());
		jsAwardRecordykj.setStatus(1);
		HashMap<String,Object> paramsMap=new HashMap<String,Object>();
		paramsMap.put("darwTime", new Date());
		paramsMap.put("status", 1);
	 
		 
		jsAwardRecordykj = jsAwardRecordService.findOne(paramsMap);
		if(jsAwardRecordykj!=null){
			jsAwardRecord=jsAwardRecordykj;
		}
		JsAwardRecord jsAwardRecordyff = new JsAwardRecord();
		paramsMap.put("darwTime", new Date());
		paramsMap.put("status", 2);
		jsAwardRecordyff = jsAwardRecordService.findOne(paramsMap);
		
		if(jsAwardRecordyff==null){
			jsAwardRecord=jsAwardRecordykj;
		}else if(jsAwardRecordykj==null){
			jsAwardRecord=jsAwardRecordyff;
		}else {
			jsAwardRecord=jsAwardRecordykj;
			if(jsAwardRecordyff.getMoneyUpdateTime().getTime()-jsAwardRecord.getMoneyUpdateTime().getTime()>0){
				jsAwardRecord=jsAwardRecordyff;
			}
		}
 
		JsAwardRecord awardRecordnew = new JsAwardRecord();
		paramsMap.clear();
		paramsMap.put("status", 0);
		awardRecordnew = jsAwardRecordService.findOne(paramsMap);
		request.setAttribute("isApp", isApp);
		request.setAttribute("clientType", clientType);
		if(jsAwardRecord!=null){
			if(jsAwardRecord.getUserName()!=null&&StringUtils.isNotBlank(jsAwardRecord.getUserName())){
				jsAwardRecord.setUserName(jsAwardRecord.getUserName().substring(0,1)+"**");
			}
			if(jsAwardRecord.getPhone()!=null&&StringUtils.isNotBlank(jsAwardRecord.getPhone())){
				jsAwardRecord.setPhone("尾号"+jsAwardRecord.getPhone().substring(7,jsAwardRecord.getPhone().length()));
			}
		}
 
		 SimpleDateFormat  dateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		 String compareDate=dateFormat.format(getNeedDate());
		 request.setAttribute("awardRecordnew",awardRecordnew );
		 
		
		String ge="0";
		String shi="0";
		String bai="0";
		String qian="0";
		String wan="0";
		String shiwan="0";
		if(awardRecordnew!=null){
			if(awardRecordnew.getAwardMoney()!=null){
				BigDecimal currentAwardMoney=awardRecordnew.getAwardMoney();
				String temp=currentAwardMoney.toString();
				if(currentAwardMoney.longValue()<10){
					ge=currentAwardMoney.toString();
				}else if(currentAwardMoney.longValue()<100){
					shi=temp.substring(0, 1);
					ge=temp.substring(1, 2);
		
				}else if(currentAwardMoney.longValue()<1000){
					
					bai=temp.substring(0, 1);
					shi=temp.substring(1, 2);
					ge=temp.substring(2, 3);
				}else if(currentAwardMoney.longValue()<10000){
					qian=temp.substring(0, 1);
					bai=temp.substring(1, 2);
					shi=temp.substring(2, 3);
					ge=temp.substring(3, 4);
				}else if(currentAwardMoney.longValue()<100000){
					wan=temp.substring(0, 1);
					qian=temp.substring(1, 2);
					bai=temp.substring(2, 3);
					shi=temp.substring(3, 4);
					ge=temp.substring(4, 5);
				}else if(currentAwardMoney.longValue()<1000000){
					shiwan=temp.substring(0, 1);
					wan=temp.substring(1, 2);
					qian=temp.substring(2, 3);
					bai=temp.substring(3, 4);
					shi=temp.substring(4, 5);
					ge=temp.substring(5, 6);
				}
			}
		}
		
		request.setAttribute("gewei",ge );
		request.setAttribute("shi",shi );
		request.setAttribute("bai",bai );
		request.setAttribute("qian",qian );
		request.setAttribute("wan",wan );
		request.setAttribute("shiwan",shiwan );		 
		request.setAttribute("compareDate",compareDate );
		request.setAttribute("jsAwardRecord", jsAwardRecord);
		request.setAttribute("downUrl", downUrl);
		return "reward/drawAwardIndex";
	}

//	@RequestMapping(value = {"drawAwardList", ""})E
//	public WebResultJson drawAwardList(HttpServletRequest request,
//			HttpServletResponse response, Model model) {
//		Integer pageNo = Integer.parseInt(request.getParameter("pageNo"));
//		Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
//		JsAwardRecord jsAwardRecord = new JsAwardRecord();
//		Page<JsAwardRecord> page = jsAwardRecordService.findPageList(pageNo,
//				pageSize, jsAwardRecord);
//		request.setAttribute("jsAwardRecord", jsAwardRecord);
//		// model.addAttribute(page);
//		// SpringUtils.renderJson(response,page);
//		Map models = new HashMap();
//		models.put("pageTotal", page.getLast());
//		models.put("list", page);
//		models.put("success", true);
//		return new WebResultJson("200", "查询成功", true, models);
//
//	}
	
	
	
	/**
	 * 获取本周五18点
	 * @return
	 */
	public static Date getCurrentDayOfWeek_five(){
		Date returnDate=new Date();
		 SimpleDateFormat  dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		  Calendar cal = Calendar.getInstance();  
         cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH),18, 0, 0);  
	        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);  
		 
		   Calendar calendar = Calendar.getInstance();
		   calendar.setTime(cal.getTime());  
	        calendar.add(Calendar.DAY_OF_WEEK,4); 
	        returnDate=calendar.getTime();
//	        System.out.println("本周五18点："+dateFormat.format( returnDate));
		return returnDate;
	}
	/**
	 * 获取下周五18点
	 * @return
	 */
	public static Date getNextDayOfWeek_five(){
		Date returnDate=new Date();
		 SimpleDateFormat  dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		  Calendar cal = Calendar.getInstance();  
         cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH),18, 0, 0);  
	        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);  
		   Calendar calendar = Calendar.getInstance();
		   calendar.setTime(cal.getTime());  
	        calendar.add(Calendar.DAY_OF_WEEK,4); 
	        calendar.add(Calendar.DAY_OF_YEAR,7); 
	        returnDate=calendar.getTime();
//	        System.out.println("下周五18点："+dateFormat.format( returnDate));
		return returnDate;
	}
	
	/**
	 * 获取需要比对的时间
	 * @return
	 */
	public static Date getNeedDate(){
		
		Date returnDate=new Date();
//		 String datenow="2016-12-09 18:00:00";
//		 try {
//			returnDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datenow);
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		Date currentDayOfWeek_five=getCurrentDayOfWeek_five();
		if(currentDayOfWeek_five.getTime()-returnDate.getTime()>0){
			returnDate=currentDayOfWeek_five;
		}else{
			returnDate=getNextDayOfWeek_five();
		}
		
		 
		return returnDate;
	}
	
	/**
	 * 检查ip白名单
	 * 
	 * @param request
	 * @param toDo
	 *             
	 * @return  
	 */
	public   ServiceResult checkIpBlack(HttpServletRequest request) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {

			String requestIp = RequestUtils.getIpAddr();

//			System.out.println("checkOutRequest ip=" + requestIp + ",params="
//					+ request.getQueryString());
//			jedisCluster.setex(BorrowOrder.REVIEW_BORROW + borrowOrder.getId(), BorrowOrder.REVIEW_BORROW_SECOND, value);
			// Thread.sleep(10000);
			String checkIpIsopen=jedisCluster.get("checkIpIsopen");
			if(checkIpIsopen==null){
//				checkIpIsopen =DictUtils.getDictLabel("checkIp_IsOpen", "awardMoney", "");// ip开关，1开，2关
				jedisCluster.setex("checkIpIsopen", 0, checkIpIsopen);
			}
			
			String ipWhite=jedisCluster.get("ipWhite");
			if(ipWhite==null){
//				ipWhite =DictUtils.getDictLabel("ip_white", "awardMoney", "");// ip开关，1开，2关
				jedisCluster.setex("ipWhite", 0,ipWhite );
			}
 
//			String ips[] = new String[]{"127.0.0.1", "localhost"};
			String ips[] = ipWhite.split(";");
			Boolean ipfalse = false;
			if (checkIpIsopen.equals("1")) {
				for (String ip : ips) {
					if (ip.equals(requestIp)) {
						ipfalse = true;
						break;
					}
				}
			} else {
				ipfalse = true;
			}
			if (ipfalse) {
				serviceResult = new ServiceResult(ServiceResult.SUCCESS,
						"IP验证通过！");
				serviceResult.setExt(requestIp);

			} else {
				serviceResult.setMsg(requestIp + "IP不在白名单内！");
			}

		} catch (Exception e) {
			serviceResult.setCode("500");
		}
		return serviceResult;
	}
}